package com.ecy.quadratic.adapter;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.ecy.quadratic.R;
import com.ecy.quadratic.adapter.recycle.RecyclingPagerAdapter;
import com.ecy.quadratic.reader.utils.ScreenUtils;
import com.yuyh.easyadapter.glide.GlideCompressTransform;

import java.util.List;

public class ImagePagerAdapter extends RecyclingPagerAdapter {

    private Context context;
    private List<Integer> imageIdList;

    private int size;
    private boolean isInfiniteLoop;

    public ImagePagerAdapter(Context context, List<Integer> imageIdList) {
        this.context = context;
        this.imageIdList = imageIdList;
        this.size = getSize(imageIdList);
        isInfiniteLoop = false;
    }

    public int getSize(List<Integer> list) {
        return list == null ? 0 : list.size();
    }

    @Override
    public int getCount() {
        // Infinite loop
        return isInfiniteLoop ? Integer.MAX_VALUE : getSize(imageIdList);
    }

    /**
     * get really position
     *
     * @param position
     * @return
     */
    private int getPosition(int position) {
        return isInfiniteLoop ? position % size : position;
    }

    @Override
    public View getView(final int position, View view, ViewGroup container) {
        if (view == null) {
            view = new ImageView(context);
            ((ImageView) view).setScaleType(ImageView.ScaleType.MATRIX);
            view.setBackgroundResource(R.drawable.cover_default_broad);
        }

        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                ComicDetailActivity.startActivity(context,"83772",imageIdList.get(getPosition(position)));
            }
        });
        Glide.with(context).load(imageIdList.get(getPosition(position))).diskCacheStrategy(DiskCacheStrategy.SOURCE).transform(new GlideCompressTransform(context, ScreenUtils.getScreenWidth())).into((ImageView) view);
        return view;
    }

    /**
     * @return the isInfiniteLoop
     */
    public boolean isInfiniteLoop() {
        return isInfiniteLoop;
    }

    /**
     * @param isInfiniteLoop the isInfiniteLoop to set
     */
    public ImagePagerAdapter setInfiniteLoop(boolean isInfiniteLoop) {
        this.isInfiniteLoop = isInfiniteLoop;
        return this;
    }

    private static class ViewHolder {

        ImageView imageView;
    }
}